﻿using SixLabors.Fonts;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Drawing;
using SixLabors.ImageSharp.Drawing.Processing;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;

namespace Polaris.Common
{
    /// <summary>
    /// 登录验证码生成类
    /// </summary>
    public static class VierificationCode
    {
        private static readonly string[] _chars = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "P", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };

        /// <summary>
        /// 生成四位随机码
        /// </summary>
        /// <returns></returns>
        public static string RandomText(int codeLength = 4)
        {
            string code = "";//产生的随机数
            int temp = -1;
            Random rand = new Random();
            for (int i = 1; i <= codeLength; i++)
            {
                if (temp != -1)
                {
                    rand = new Random(i * temp * unchecked((int)DateTime.Now.Ticks));
                }
                int t = rand.Next(61);
                if (temp != -1 && temp == t)
                {
                    return RandomText();
                }
                temp = t;
                code += _chars[t];
            }
            return code;
        }

        private static readonly Color[] Colors =
        {
            Color.Black, Color.Red, Color.DarkBlue,
            Color.Green, Color.Orange, Color.Brown,
            Color.DarkCyan, Color.Purple
        };

        private static readonly string[] FontNames =
        {
            "Arial", "Verdana", "Comic Sans MS"  // 优先使用跨平台字体
        };

        /// <summary>
        /// 生成验证码图片
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static string CreateBase64Image(string code)
        {
            var random = new Random();
            int width = 110;
            int height = 40;

            // 初始化字体系统（自动加载系统字体）
            var fontCollection = new FontCollection();
            FontFamily fontFamily;
            foreach (var fontName in FontNames)
            {
                if (SystemFonts.TryGet(fontName, out fontFamily))
                {
                    fontCollection.AddSystemFonts();
                }
            }

            // 创建图像并设置背景
            using var image = new Image<Rgba32>(width, height);
            image.Mutate(ctx => ctx.Fill(Color.White));

            // 绘制干扰点
            for (int i = 0; i < 100; i++)
            {
                int x = random.Next(width);
                int y = random.Next(height);
                image.Mutate(ctx => ctx.DrawLine(
                    Color.LightGray,
                    0.5f,
                    new PointF(x, y),
                    new PointF(x + 1, y + 1)
                ));
            }

            // 测量文本尺寸
            var fontFamily2 = fontCollection.Families.Count() > 0
                ? fontCollection.Families.FirstOrDefault()
                : SystemFonts.Families.First();

            var textOptions = new TextOptions(new Font(fontFamily2, 15, FontStyle.Bold))
            {
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment = VerticalAlignment.Top
            };

            var textSize = TextMeasurer.MeasureSize(code, textOptions);

            // 计算居中位置
            float startX = 20;
            float startY = (height - textSize.Height) / 2;

            // 绘制每个字符
            float currentX = startX;
            var count = fontCollection.Families.Count();
            foreach (char c in code)
            {
                // 随机选择字体和颜色
                var font = new Font(
                    fontCollection.Families.ToList()[/*random.Next(30)*/0],
                    25,
                    FontStyle.Bold
                );

                var color = Colors[random.Next(Colors.Length)];

                // 测量单个字符
                var charSize = TextMeasurer.MeasureSize(c.ToString(), new TextOptions(font));

                // 绘制字符
                image.Mutate(ctx => ctx.DrawText(
                    c.ToString(),
                    font,
                    color,
                    new PointF(currentX, startY + (textSize.Height - charSize.Height) / 2)
                ));

                currentX += charSize.Width + 7;
            }

            var pen = Pens.DashDot(Color.Silver, 1);
            //绘制干扰线
            for (var k = 0; k < 20; k++)
            {
                PointF[] points = new PointF[2];
                points[0] = new PointF(random.Next(width), random.Next(height));
                points[1] = new PointF(random.Next(width), random.Next(height));
                image.Mutate(x => x.DrawLine(pen, points));
            }

            // 转换为 Base64
            using var stream = new MemoryStream();
            image.SaveAsJpeg(stream);
            return Convert.ToBase64String(stream.ToArray());
        }

        //public static string CreateBase64Imgage(string code)
        //{
        //    Random random = new Random();
        //    //验证码颜色集合
        //    Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
        //    //验证码字体集合
        //    string[] fonts = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };

        //    //using var img = new Bitmap((int)code.Length * 18, 70);
        //    using var img = new Bitmap(110, 40);

        //    using var g = Graphics.FromImage(img);
        //    g.Clear(Color.White);//背景设为白色

        //    //在随机位置画背景点
        //    for (int i = 0; i < 100; i++)
        //    {
        //        int x = random.Next(img.Width);
        //        int y = random.Next(img.Height);
        //        g.DrawRectangle(new Pen(Color.LightGray, 0), x, y, 1, 1);
        //    }
        //    //验证码绘制在g中
        //    for (int i = 0; i < code.Length; i++)
        //    {
        //        int cindex = random.Next(7);//随机颜色索引值
        //        int findex = random.Next(5);//随机字体索引值
        //        Font f = new Font(fonts[findex], 15, FontStyle.Bold);//字体
        //        Brush b = new SolidBrush(c[cindex]);//颜色
        //        int ii = 4;
        //        if ((i + 1) % 2 == 0)//控制验证码不在同一高度
        //        {
        //            ii = 2;
        //        }
        //        g.DrawString(code.Substring(i, 1), f, b, 3 + (i * 12), ii);//绘制一个验证字符
        //    }
        //    using (MemoryStream stream = new MemoryStream())
        //    {
        //        img.Save(stream, ImageFormat.Jpeg);
        //        byte[] b = stream.ToArray();
        //        return Convert.ToBase64String(stream.ToArray());
        //    }
        //}
    }
}
